package com.migraine.controller;


import com.alibaba.fastjson.JSONObject;
import com.migraine.model.Relationship;
import com.migraine.model.Rooms;
import com.migraine.model.Users;
import com.migraine.service.RelationshipService;
import com.migraine.service.RoomsService;
import com.migraine.service.UsersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.Semaphore;

@Controller
@RequestMapping("/room")
@ResponseBody
public class RoomController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RoomsService roomsService;

    @Autowired
    private RelationshipService relationshipService;

    // 日志工具
    private static final Logger logger = LoggerFactory.getLogger(RoomController.class);

    Semaphore deleteRoomSep = new Semaphore(1);

    Semaphore addFriendSep = new Semaphore(1);

    /**
     * 请求格式/room/getUserInfo?uid=
     * 获取房间内用户的信息，传入用户uid
     *
     * @return 返回用户数据（不含密码）
     */
    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam String uid) {

        Users user = usersService.getUsers(Integer.parseInt(uid));
        user.setPassword(null);
        JSONObject json = new JSONObject();
        json.put("user", user);
        return json.toJSONString();
    }

    /**
     * 传入房间号，返回房主信息房间信息
     *
     * @param roomId 房间号
     * @return 房主信息
     */
    @GetMapping("/getRoomCreaterInfo")
    public String getRoomCreaterInfo(@RequestParam String roomId) {

        Rooms room = roomsService.getRoomsById(Integer.parseInt(roomId));

        Users user = usersService.getUsers(Integer.parseInt(room.getCreator()));
        user.setPassword(null);
        JSONObject json = new JSONObject();
        json.put("creator", user);
        json.put("room", room);
        return json.toJSONString();
    }

    /**
     * 删除房间
     *
     * @param roomid
     * @return
     */
    @GetMapping("deleteRoom")
    public String deleteRoom(@RequestParam String roomid) {
        boolean ans = false;
        int rmid = Integer.parseInt(roomid);
        int availablePermits = deleteRoomSep.availablePermits();
        if (availablePermits > 0) {
            try {
                deleteRoomSep.acquire(1);
                if (roomsService.deleteRoom(rmid)) ans = true;
            } catch (InterruptedException e) {
                logger.error("错误：",e);
                Thread.currentThread().interrupt();
            } finally {
                deleteRoomSep.release(1);
            }
        }
        JSONObject json = new JSONObject();
        json.put("ans", ans);
        return json.toJSONString();
    }

    /**
     * 填加好友
     *
     * @param map
     * @return
     */
    @PostMapping("addFriend")
    public String addFriend(@RequestBody Map<String, String> map) {
        String userId = map.get("uid");
        String friendId = map.get("friendid");
        Users user = usersService.getUsers(Integer.parseInt(userId));
        Users friend = usersService.getUsers(Integer.parseInt(friendId));
        int relationshipid1 = relationshipService.getid(user.getUid(), friend.getUid());
        int relationshipid2 = relationshipService.getid(friend.getUid(), user.getUid());
        String er = "0";
        if (userId.equals(friendId)) {
            // 两者id一样 设置er为3
            er = "3";
        } else if (relationshipid1 != -1 || relationshipid2 != -1) {
            // 两者已经是好友则设置er为1
            er = "1";
        } else {
            int availablePermits = addFriendSep.availablePermits();
            if (availablePermits > 0) {
                try {
                    addFriendSep.acquire(1);
                    boolean ans1 = relationshipService.insertRelationship(user.getUid(), friend.getUid());
                    boolean ans2 = relationshipService.insertRelationship(friend.getUid(), user.getUid());
                    if (ans1 && ans2) {
                        // 成功添加则设置er为2
                        er = "2";
                    }
                } catch (InterruptedException e) {
                    logger.error("错误：",e);
                    Thread.currentThread().interrupt();
                } finally {
                    addFriendSep.release(1);
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("er", er);
        return json.toJSONString();
    }

}
